package com.dyz.leetcode._14_binarySearchTree;

import com.dyz.leetcode.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class _106_buildTree {
    private int[] postorder;
    private int rootIndex=postorder.length-1;
    private Map<Integer, Integer> idMap = new HashMap<>();
    public TreeNode buildTree( int[] inorder, int[] postorder) {
        this.postorder = postorder;
        for(int i =0; i<inorder.length; i++){
            idMap.put(inorder[i], i);
        }
        return buildTree1(0, inorder.length-1);

    }
    public TreeNode buildTree1(int left, int right){
        if (left > right) {return null;}

        int rootVal = postorder[rootIndex];
        rootIndex--;
        TreeNode root = new TreeNode(rootVal);
        int mid = idMap.get(rootVal);

        root.right = buildTree1(mid + 1, right);
        return root;
    }
}
